package org.liaohailong.victorlibrary.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.liaohailong.library.util.ContentKits
import org.liaohailong.library.util.ThumbHelper
import org.liaohailong.victorlibrary.R
import org.liaohailong.victorlibrary.base.BaseActivity
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread

/**
 * Describe: 视频缩略图演示
 *
 *
 * @author liaohailong
 * Time: 2020/10/29 13:54
 */
class ThumbActivity : BaseActivity() {
    companion object {
        const val REQUEST_VIDEO = 0
        fun show(context: Context) {
            val intent = Intent(context, ThumbActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val thumbHelper = ThumbHelper(this)
    private val mainHandler = Handler(Looper.getMainLooper())
    private val listAdapter: CustomAdapter = CustomAdapter(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_thumb)
        findViewById<View>(R.id.btn_find).setOnClickListener {
            val intent = Intent()
            intent.action = Intent.ACTION_PICK
            intent.type = "video/*"
            startActivityForResult(intent, REQUEST_VIDEO)
        }

        findViewById<RecyclerView>(R.id.lv_thumb).apply {
            layoutManager = LinearLayoutManager(this@ThumbActivity,
                    RecyclerView.HORIZONTAL, false)
            adapter = listAdapter
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (Activity.RESULT_OK != resultCode) {
            return
        }

        if (requestCode == REQUEST_VIDEO) {
            data?.apply {
                val uri = getData() ?: return
                val videoFile = generateVideoFile()
                if (copyResult(uri, videoFile)) {
                    // 复制成功，开始解码
                    getThumb(videoFile.absolutePath)
                }
            }
        }
    }

    private fun generateVideoFile(): File {
        val dir = externalCacheDir
        val fileName = "video_${System.currentTimeMillis()}"
        return File(dir, fileName)
    }

    private fun copyResult(uri: Uri, dstFile: File): Boolean {
        val storage = ContentKits.isStorage(uri)
        val path = if (storage) uri.path else ContentKits.getPath(this, uri)
        if (!File(path!!).exists()) {
            mainHandler.post {
                Toast.makeText(this, "原图已被删除，请选择其他图片", Toast.LENGTH_SHORT).show()
            }
            return false
        }

        var fis: FileInputStream? = null
        var fos: FileOutputStream? = null
        try {
            fis = if (storage) FileInputStream(File(path)) else {
                val pfd: ParcelFileDescriptor = contentResolver.openFileDescriptor(uri, "r")!!
                val fd = pfd.fileDescriptor
                FileInputStream(fd)
            }
            fos = FileOutputStream(dstFile)
            val byteArray = ByteArray(1024 * 8)
            var len = 0
            len = fis.read(byteArray, 0, byteArray.size)
            while (len != -1) {
                fos.write(byteArray, 0, len)
                len = fis.read(byteArray, 0, byteArray.size)
            }
            return true
        } catch (e: Exception) {
            e.printStackTrace()
            try {
                fis?.close()
            } catch (ex: Exception) {
                ex.printStackTrace()
            }
            try {
                fos?.close()
            } catch (ex: Exception) {
                ex.printStackTrace()
            }
            return false
        }
    }


    private fun getThumb(filePath: String) {
        listAdapter.clear()
        thread {
            val videoInfo = thumbHelper.getVideoInfo(filePath)
            val inSampleSize = 2
            val start = 50
            val interval = (videoInfo.durationMs / 9).toInt()
            val taskTag = thumbHelper.start(filePath, inSampleSize, start, interval, object : ThumbHelper.OnThumbReadCallback {
                override fun onThumbRead(it: ThumbHelper.ThumbInfo) {
                    mainHandler.post {
                        Log.i("Victor", it.toString())
                        listAdapter.addItem(it)
                    }
                }

                override fun onThumbReadComplete() {
                    //
                }
            })
        }

    }

    class CustomAdapter(val context: Context) : RecyclerView.Adapter<CustomViewHolder>() {
        private val data: MutableList<ThumbHelper.ThumbInfo> = mutableListOf()

        fun addItem(thumbInfo: ThumbHelper.ThumbInfo) {
            data.add(thumbInfo)
            notifyDataSetChanged()
        }

        fun clear() {
            data.clear()
            notifyDataSetChanged()
        }

        override fun getItemCount(): Int {
            return data.size
        }

        override fun getItemId(position: Int): Long {
            return data[position].hashCode().toLong()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.layout_thumb_item, parent, false)
            return CustomViewHolder(view)
        }

        override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
            holder.ivThumb.setImageBitmap(data[position].bitmap)
            val format = SimpleDateFormat("mm:ss:SS")
            val time = format.format(Date().apply { time = data[position].timeMs })
            holder.tvNumber.text = "${position + 1}\n$time"

        }
    }

    class CustomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvNumber: TextView = itemView.findViewById(R.id.tv_number)
        val ivThumb: ImageView = itemView.findViewById(R.id.iv_thumb)
    }
}